package com.elite.groovy.callback

import cn.com.elite.PropertiesUtil
import cn.com.kh.HttpClientProxy
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/*
 * 根据名单状态查询小结为预约(OPEN)状态的、并且是预测式外呼批次的名单加入到临时表中、临时表推送标记is_push标记为2(预约专用)，推送类型标记为3(预约)、时间范围为预约当天及当天之前的预约名单，当日第一次执行时候启用，多次执行不重复添加
 * 根据历史表查询当天推送给青牛的名单中推送类型为3（预约）的，并且没有接通电话的并且当天不存在录音的(不存在录音)
 * 将标记为2的数据全部推送给青牛并加入到历史表中,并清空临时表
 * 
 */
class autoQnReservationPreCall implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(autoQnReservationPreCall.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		
		log.debug("开始启动青牛预测外呼预约名单下发");
		JSONObject result = new JSONObject();
		long startTime=System.currentTimeMillis();
		def count = 0;
		try {
			//获取配置文件中配置好的企业号、代理ip及端口
			PropertiesUtil cfg = new PropertiesUtil();
			def Te_entId = cfg.readValue("QingNiu.EntId");
			String proxyIp = cfg.readValue("QingNiu.ProxyIP");
			int proxyPort=0;
			if(cfg.readValue("QingNiu.ProxyPort")!=null&&cfg.readValue("QingNiu.ProxyPort")!="") {
				proxyPort = cfg.readValue("QingNiu.ProxyPort").toInteger();
			}
			
            //查询当天是否为节假日
			//def seleteSQL3="select case when count(*) > 0 then '1'  else '0' end con1 from c_freedate where freedate = //to_date(to_char(sysdate,'yyyy-mm-dd'),'yyyy/mm/dd')";
			//def result1=eliteBean.chaxun_sql(seleteSQL3, "dataSource");
			//def queryMap2=result1[0];
			//def holiyday = queryMap2.get("CON1");
			//log.debug("当天是否节假日:"+holiyday);
			//if(holiyday=='0'){
			/*根据名单状态查询小结为预约(OPEN)状态的、并且是预测式外呼批次、时间范围为预约当天及当天之前的预约名单加入到临时表中、临时表推送标记is_push标记为2(预约专用)，
			推送类型标记为3(预约)，当日第一次执行时候启用，多次执行不重复添加*/
			def seleteSQL1="insert into list_push_temporary (id, customer_guid,  customer_name, mobile, tel_1, atel_1, atel_2, atel_3,atel_4, createddate, createdby, in_enddate, custlist, activity_name,send_type, is_push,  objective_guid) select sys_guid(),   c.customer_guid,  c2.customername,   c2.mobile,   c2.tel_1,c2.atel_1,  c2.atel_2,   c2.atel_3,   c2.atel_4,  sysdate,   'SELITE',  c.in_enddate, c.stringfield1,  b.reservation_activity, '3',  '2', objective_guid from elitetask e  left join customer c  on c.customer_guid = e.customer_guid left join customer c2   on c.parent_guid = c2.customer_guid inner join Inflow_rule_configuration l   on e.custlistname = l.custlist_name  inner join Batch_configuration b on l.activity_name = b.id left join authority_relationship a on e.handlegroup_id=a.lower where 1 = 1 and ((e.expectstarttime <= (TRUNC(SYSDATE) + 1 - 1 / 86400)) or  e.expectstarttime >= trunc(sysdate + 3))  and e.handleby_id is not null  and e.attempt > 0 and e.elitetaskstatus <> 'APCALL' and c.customertype2_id = '000002'   and c.stringfield16 is null and to_date(to_char(c.in_enddate,'mm-dd'),'mm-dd') - sysdate>7 and  a.higher not in (select c.createdgroup from c_freedate c  where c.freedate=trunc(sysdate)) order by e.elitetaskstatus, c.in_enddate asc";
			def row1=eliteBean.update(seleteSQL1,"dataSource");
			log.debug("当日应推送预约数量(当日+当日之前的预约):"+row1);
			if(row1>0){
				String selectSQL3="select WEBSERVICEURL from sysc_interface where webtype='QN_MDDR'";
				
				def postURL2=eliteBean.chaxun_sql(selectSQL3, "dataSource");
				def httpURL=postURL2[0].get("WEBSERVICEURL");
				log.debug("青牛地址:"+httpURL);
				JSONObject dataObject2 = null;
				def sendNum=2700; //每批数据分批推送条数
				def con = Math.ceil(row1/sendNum);
				for(int q=1;q<=con;q++) {
				    def temp_id=UUID.randomUUID().toString();
					def updateSQL1="update list_push_temporary set Is_push='1',temp_id='"+temp_id+"' where Is_push='2' and send_type =3 and rownum<='"+sendNum+"'";
					int row4=eliteBean.update(updateSQL1,"dataSource");
					
					//将临时表中标记为预约待下发(is_push标记为2)的名单查询出来转为报文推送给青牛
					String sqls="select l.customer_guid custId,"+Te_entId+" ENTID,l.activity_name CALLLISTNAME,l.customer_guid recordKey,l.mobile,l.tel_1,l.atel_1,l.atel_2,l.atel_3,l.atel_4,s.Agent_Id,s.Staff_Id, l.objective_guid from list_push_temporary l  left join elitetask e on l.objective_guid = e.objective_guid left join staff s  on e.handleby_id = s.Staff_Id where l.Is_push = '1'and l.send_type = 3 and l.temp_id = '"+temp_id+"'  and e.objective_guid is not null order by in_enddate asc";
					def resultlist2= eliteBean.chaxun_sql(sqls, "dataSource");
					
					JSONArray jsonArray2=JSONArray.fromObject(resultlist2);
					def ListNum2 = jsonArray2.size();
					JSONArray arr = new JSONArray();
					JSONObject obj = new JSONObject();
					JSONObject dataObject= null;;
					log.debug("temp_id:"+temp_id+"本次调用数量:"+ListNum2);
					for(int j=0;j<ListNum2;j++) {
						dataObject=jsonArray2.getJSONObject(j);
						def cust_id=GetJV(dataObject, "CUSTID");
						def entId=GetJV(dataObject, "ENTID");
						def activity_id=GetJV(dataObject, "CALLLISTNAME");
						def recordKey=GetJV(dataObject, "RECORDKEY");
						def objectiveGuid = GetJV(dataObject, "OBJECTIVE_GUID");
						def agentId = GetJV(dataObject, "AGENT_ID");
						def staffId = GetJV(dataObject, "STAFF_ID");
						def phoneNumber1=GetJV(dataObject, "MOBILE");
						def phoneNumber2=GetJV(dataObject, "TEL_1");
						def phoneNumber3=GetJV(dataObject, "ATEL_1");
						def phoneNumber4=GetJV(dataObject, "ATEL_2");
						def phoneNumber5=GetJV(dataObject, "ATEL_3");
						def phoneNumber6=GetJV(dataObject, "ATEL_4");
						if(objectiveGuid==null || objectiveGuid=="") {
							continue;
						}
						JSONObject phoneNumbers = new JSONObject();
						phoneNumbers.put("phoneNumber1", phoneNumber1);
						phoneNumbers.put("phoneNumber2", phoneNumber2);
						phoneNumbers.put("phoneNumber3", phoneNumber3);
						phoneNumbers.put("phoneNumber4", phoneNumber4);
						phoneNumbers.put("phoneNumber5", phoneNumber5);
						phoneNumbers.put("phoneNumber6", phoneNumber6);
						obj.put("custId", cust_id+","+objectiveGuid);
						obj.put("entId", entId);
						obj.put("callListName", activity_id);
						obj.put("recordKey", recordKey);
						obj.put("phoneNumbers", phoneNumbers);
						obj.put("exData3",agentId);
						obj.put("exData4",staffId);
						obj.put("exData5",objectiveGuid);
						obj.put("exData6",objectiveGuid);
						
						arr.add(obj);
					}
					
					//推送数据
					def id=UUID.randomUUID().toString();
					JSONObject objtwo = new JSONObject();
					objtwo.put("batchId", id);
					objtwo.put("total", ListNum2);
					objtwo.put("data", arr);
					
					long time=System.currentTimeMillis();
					def reJson = HttpClientProxy.sendPost(httpURL, objtwo.toString(),proxyIp,proxyPort);
					log.debug(id+"本次调用返回结果:"+reJson);
					JSONObject json = new JSONObject().fromObject(reJson);
					log.debug(id+"本次调用返回结果转换:"+json.toString());
					long etime=System.currentTimeMillis();
					log.debug(id+"本次调用时间耗时:"+(etime - startTime));
					
					String code=json.code;
					StringBuffer sql = new StringBuffer("insert into list_push_history ");
					sql.append("(id,batch_id,customer_guid,is_flag,activity_name,custlist,");
					sql.append("createddate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,objective_guid) ");
					sql.append("select sys_guid(),id,customer_guid,'"+code+"',activity_name,custlist,");
					sql.append("sysdate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,objective_guid ");
					sql.append("from list_push_temporary where is_push='1' and send_type =3 and temp_id='"+temp_id+"'");
					log.debug(id+"本次推送记录sql:"+sql.toString());
					def row7=eliteBean.update(sql.toString(),"dataSource");
					log.debug(id+"本次推送记录至历史表数量:"+row7);
					count+=row7;
					
					def deleteSQL1="delete from list_push_temporary where is_push='1' and send_type=3 and temp_id='"+temp_id+"' and Listrank is null"
					log.debug(id+"本次推送清除临时表sql:"+deleteSQL1);
					int row6=eliteBean.update(deleteSQL1,"dataSource");
					log.debug(id+"本次推送清除临时表数量:"+row6);
						
					long endTime=System.currentTimeMillis();
					result.put("code", 1);
					result.put("msg", "处理完成、调用处理时长(毫秒):" + (endTime - startTime) + "共推送" + count + "条");
					log.debug("青牛预测外呼预约名单下发结束");
					
				}
			}else {
				result.put("code", 1007);
				result.put("msg", "当前日期是没有预约名单不流入");
			}
		}catch(Exception e) {
			result.put("code", 1008);
			result.put("msg", e.getMessage());
		}
	}
	
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null
		try {
			Rev_Value = inJson.getString(getKey)
			//log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey))
				//log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
			} catch (Exception e1) {
				Rev_Value = ""
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = ""
			}
		}
		return Rev_Value
	}
}